<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores';

const router = useRouter();
const userStore = useUserStore();

// 地址列表数据
const addresses = ref([
  {
    id: 1,
    name: '张三',
    phone: '13812345678',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    detail: '建国路88号中央公园12号楼2单元501室',
    isDefault: true
  },
  {
    id: 2,
    name: '李四',
    phone: '13987654321',
    province: '上海市',
    city: '上海市',
    district: '浦东新区',
    detail: '陆家嘴环路1000号金融中心25楼',
    isDefault: false
  },
  {
    id: 3,
    name: '王五',
    phone: '13765432198',
    province: '广东省',
    city: '广州市',
    district: '天河区',
    detail: '珠江新城冼村路28号',
    isDefault: false
  }
]);

// 新增地址表单数据
const newAddress = ref({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
});

// 省市区选项
const provinces = ref(['北京市', '上海市', '广东省', '江苏省']);
const cities = ref(['北京市']);
const districts = ref(['朝阳区', '海淀区', '东城区', '西城区']);

// 编辑状态
const editingId = ref(null);
const showAddForm = ref(false);

// 组件挂载时初始化
onMounted(() => {
  userStore.initializeAuth();
});

// 方法
const setDefault = (addressId: number) => {
  addresses.value.forEach(addr => {
    addr.isDefault = addr.id === addressId;
  });
};

const editAddress = (address: any) => {
  editingId.value = address.id;
  newAddress.value = { ...address };
  showAddForm.value = true;
};

const deleteAddress = (addressId: number) => {
  if (confirm('确定要删除这个地址吗？')) {
    addresses.value = addresses.value.filter(addr => addr.id !== addressId);
  }
};

const saveAddress = () => {
  // 表单验证
  if (!newAddress.value.name || !newAddress.value.phone || !newAddress.value.detail) {
    alert('请填写完整的地址信息');
    return;
  }

  if (editingId.value) {
    // 编辑地址
    const index = addresses.value.findIndex(addr => addr.id === editingId.value);
    if (index !== -1) {
      addresses.value[index] = { ...newAddress.value };
    }
  } else {
    // 新增地址
    const newId = Math.max(...addresses.value.map(addr => addr.id)) + 1;
    addresses.value.push({
      ...newAddress.value,
      id: newId
    });
  }

  // 如果设为默认，取消其他默认地址
  if (newAddress.value.isDefault) {
    addresses.value.forEach(addr => {
      if (addr.id !== newAddress.value.id) {
        addr.isDefault = false;
      }
    });
  }

  resetForm();
};

const resetForm = () => {
  newAddress.value = {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  };
  editingId.value = null;
  showAddForm.value = false;
};

const showNewAddressForm = () => {
  resetForm();
  showAddForm.value = true;
};

// 用户登出
const handleLogout = () => {
  userStore.logout();
  router.push('/login');
};
</script>

<template>
  <div class="min-h-screen flex flex-col" style="background-color: #f8f8f8;">
    <!-- 导航栏 -->
    <header class="bg-white p-4 border-b border-gray-200 shadow-sm">
      <div class="container mx-auto flex items-center justify-between">
        <a @click.prevent="router.push('/')" href="#" class="text-2xl font-bold text-rose-500 flex items-center">
          <font-awesome-icon icon="seedling" class="text-rose-500 mr-2" />
          花礼相伴
        </a>
        <div class="hidden lg:block w-1/3">
          <div class="relative">
            <input type="text" placeholder="搜索鲜花、场景..." 
              class="w-full pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-rose-500">
            <font-awesome-icon icon="search" class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
          </div>
        </div>
        <nav class="hidden md:flex space-x-6">
          <a @click.prevent="router.push('/')" href="#" class="text-gray-600 hover:text-rose-500">首页</a>
          <a @click.prevent="router.push('/categories')" href="#" class="text-gray-600 hover:text-rose-500">分类</a>
          <a @click.prevent="router.push('/cart')" href="#" class="text-gray-600 hover:text-rose-500">购物车</a>
        </nav>
        <div class="flex items-center space-x-4">
          <a @click.prevent="router.push('/cart')" href="#" class="p-2 relative">
            <font-awesome-icon icon="shopping-cart" class="text-gray-600 text-xl" />
            <span class="absolute top-0 right-0 bg-rose-500 text-white rounded-full text-xs w-4 h-4 flex items-center justify-center">3</span>
          </a>
          
          <!-- 未登录状态 -->
          <template v-if="!userStore.checkIsLoggedIn">
            <a @click.prevent="router.push('/login')" href="#" class="hidden md:block text-gray-600 hover:text-rose-500">登录</a>
            <a @click.prevent="router.push('/register')" href="#" class="hidden md:block text-white bg-rose-500 px-4 py-2 rounded-lg hover:bg-rose-600 transition duration-300">注册</a>
          </template>
          
          <!-- 已登录状态 -->
          <template v-else>
            <div class="hidden md:flex items-center space-x-3">
              <div class="flex items-center space-x-2">
                <img 
                  :src="userStore.getUserAvatar" 
                  :alt="userStore.getDisplayName"
                  class="w-8 h-8 rounded-full object-cover"
                >
                <span class="text-gray-700">{{ userStore.getDisplayName }}</span>
              </div>
              <div class="relative group">
                <button class="text-gray-600 hover:text-rose-500">
                  <font-awesome-icon icon="chevron-down" class="text-sm" />
                </button>
                <div class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
                  <a @click.prevent="router.push('/user-center')" href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人中心</a>
                  <a @click.prevent="router.push('/order-detail')" href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">我的订单</a>
                  <a @click.prevent="router.push('/favorites')" href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">我的收藏</a>
                  <div class="border-t border-gray-100"></div>
                  <a @click.prevent="handleLogout" href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <!-- 移动端搜索栏 -->
      <div class="mt-3 relative md:hidden">
        <input type="text" placeholder="搜索鲜花、场景..." 
          class="w-full pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-rose-500">
        <font-awesome-icon icon="search" class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
      </div>
    </header>

    <!-- 主体内容区域 -->
    <main class="flex-grow container mx-auto px-4 py-6 md:py-8">
      <div class="md:flex md:gap-6">
        <!-- 左侧导航 -->
        <div class="md:w-1/4 lg:w-1/5 mb-6 md:mb-0">
          <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <!-- 用户信息 -->
            <div class="p-4 text-center border-b border-gray-100">
              <img 
                :src="userStore.getUserAvatar" 
                :alt="userStore.getDisplayName" 
                class="w-20 h-20 rounded-full mx-auto mb-3"
              >
              <h2 class="font-bold text-lg text-gray-800">{{ userStore.getDisplayName }}</h2>
              <p class="text-gray-500 text-sm">普通会员</p>
            </div>

            <!-- 导航菜单 -->
            <nav class="p-2">
              <a @click.prevent="router.push('/user-center')" href="#" class="flex items-center p-3 rounded-lg text-gray-700 hover:bg-gray-50">
                <font-awesome-icon icon="user-circle" class="w-5 text-center mr-2" />
                <span>个人信息</span>
              </a>
              <a @click.prevent="router.push('/order-detail')" href="#" class="flex items-center p-3 rounded-lg text-gray-700 hover:bg-gray-50">
                <font-awesome-icon icon="clipboard-list" class="w-5 text-center mr-2" />
                <span>我的订单</span>
              </a>
              <a @click.prevent="router.push('/address')" href="#" class="flex items-center p-3 rounded-lg bg-rose-50 text-rose-500">
                <font-awesome-icon icon="map-marker-alt" class="w-5 text-center mr-2" />
                <span>收货地址</span>
              </a>
              <a @click.prevent="router.push('/favorites')" href="#" class="flex items-center p-3 rounded-lg text-gray-700 hover:bg-gray-50">
                <font-awesome-icon icon="heart" class="w-5 text-center mr-2" />
                <span>我的收藏</span>
              </a>
              <a @click.prevent="router.push('/review')" href="#" class="flex items-center p-3 rounded-lg text-gray-700 hover:bg-gray-50">
                <font-awesome-icon icon="comment-alt" class="w-5 text-center mr-2" />
                <span>我的评价</span>
              </a>
              <a @click.prevent="router.push('/user-center')" href="#" class="flex items-center p-3 rounded-lg text-gray-700 hover:bg-gray-50">
                <font-awesome-icon icon="cog" class="w-5 text-center mr-2" />
                <span>账号设置</span>
              </a>
            </nav>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="md:w-3/4 lg:w-4/5">
          <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex justify-between items-center mb-6 pb-2 border-b border-gray-100">
              <h2 class="text-lg font-bold text-gray-800">收货地址管理</h2>
              <button 
                @click="showNewAddressForm"
                class="flex items-center text-rose-500 hover:text-rose-600"
              >
                <font-awesome-icon icon="plus" class="mr-1" /> 新增收货地址
              </button>
            </div>
            
            <!-- 地址列表 -->
            <div class="space-y-4">
              <div 
                v-for="address in addresses" 
                :key="address.id"
                :class="[
                  'rounded-lg p-4 relative',
                  address.isDefault 
                    ? 'border-2 border-rose-500' 
                    : 'border border-gray-200 hover:border-gray-300'
                ]"
              >
                <span 
                  v-if="address.isDefault"
                  class="absolute top-0 right-0 bg-rose-500 text-white text-xs px-2 py-1 rounded-bl-lg"
                >
                  默认
                </span>
                <div class="flex justify-between items-start mb-2">
                  <div>
                    <span class="font-medium text-gray-800">{{ address.name }}</span>
                    <span class="ml-4 text-gray-600">{{ address.phone }}</span>
                  </div>
                </div>
                <p class="text-gray-600 mb-4">
                  {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
                </p>
                <div class="flex justify-between items-center">
                  <label class="inline-flex items-center">
                    <input 
                      type="checkbox" 
                      :checked="address.isDefault"
                      @change="setDefault(address.id)"
                      class="form-checkbox h-4 w-4 text-rose-500"
                    >
                    <span class="ml-2 text-gray-700">设为默认</span>
                  </label>
                  <div class="flex space-x-3 text-sm">
                    <button 
                      @click="editAddress(address)"
                      class="text-gray-500 hover:text-rose-500"
                    >
                      <font-awesome-icon icon="edit" class="mr-1" /> 编辑
                    </button>
                    <button 
                      @click="deleteAddress(address.id)"
                      class="text-gray-500 hover:text-rose-500"
                    >
                      <font-awesome-icon icon="trash" class="mr-1" /> 删除
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 新增/编辑地址表单 -->
            <div v-if="showAddForm" class="mt-8 pt-6 border-t border-gray-200">
              <h3 class="text-lg font-bold mb-4 text-gray-800">
                {{ editingId ? '编辑收货地址' : '新增收货地址' }}
              </h3>
              
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-gray-700 mb-1">收货人</label>
                  <input 
                    v-model="newAddress.name"
                    type="text" 
                    placeholder="请输入收货人姓名" 
                    class="w-full border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  >
                </div>
                <div>
                  <label class="block text-gray-700 mb-1">手机号码</label>
                  <input 
                    v-model="newAddress.phone"
                    type="text" 
                    placeholder="请输入手机号码" 
                    class="w-full border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  >
                </div>
              </div>

              <div class="mt-4">
                <label class="block text-gray-700 mb-1">所在地区</label>
                <div class="grid grid-cols-3 gap-2">
                  <select 
                    v-model="newAddress.province"
                    class="border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  >
                    <option value="">请选择省份</option>
                    <option v-for="province in provinces" :key="province" :value="province">
                      {{ province }}
                    </option>
                  </select>
                  <select 
                    v-model="newAddress.city"
                    class="border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  >
                    <option value="">请选择城市</option>
                    <option v-for="city in cities" :key="city" :value="city">
                      {{ city }}
                    </option>
                  </select>
                  <select 
                    v-model="newAddress.district"
                    class="border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                  >
                    <option value="">请选择区县</option>
                    <option v-for="district in districts" :key="district" :value="district">
                      {{ district }}
                    </option>
                  </select>
                </div>
              </div>

              <div class="mt-4">
                <label class="block text-gray-700 mb-1">详细地址</label>
                <input 
                  v-model="newAddress.detail"
                  type="text" 
                  placeholder="请输入详细地址，如街道、门牌号等" 
                  class="w-full border border-gray-300 rounded-md p-2 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent"
                >
              </div>

              <div class="mt-4">
                <label class="inline-flex items-center">
                  <input 
                    v-model="newAddress.isDefault"
                    type="checkbox" 
                    class="form-checkbox h-4 w-4 text-rose-500"
                  >
                  <span class="ml-2 text-gray-700">设为默认收货地址</span>
                </label>
              </div>

              <div class="mt-6 flex justify-center md:justify-start">
                <button 
                  @click="saveAddress"
                  class="px-6 py-2 bg-rose-500 text-white rounded-md hover:bg-rose-600 transition duration-300"
                >
                  保存地址
                </button>
                <button 
                  @click="resetForm"
                  class="ml-4 px-6 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-300"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部导航栏 - 移动端 -->
    <footer class="md:hidden mt-auto bg-white border-t border-gray-200">
      <div class="flex justify-around py-2">
        <a @click.prevent="router.push('/')" href="#" class="flex flex-col items-center px-4 py-2 text-gray-500">
          <font-awesome-icon icon="home" class="text-lg" />
          <span class="text-xs mt-1">首页</span>
        </a>
        <a @click.prevent="router.push('/categories')" href="#" class="flex flex-col items-center px-4 py-2 text-gray-500">
          <font-awesome-icon icon="th-large" class="text-lg" />
          <span class="text-xs mt-1">分类</span>
        </a>
        <a @click.prevent="router.push('/cart')" href="#" class="flex flex-col items-center px-4 py-2 text-gray-500">
          <font-awesome-icon icon="shopping-cart" class="text-lg" />
          <span class="text-xs mt-1">购物车</span>
        </a>
        <a @click.prevent="router.push('/user-center')" href="#" class="flex flex-col items-center px-4 py-2 text-gray-500">
          <font-awesome-icon :icon="['far', 'user']" class="text-lg" />
          <span class="text-xs mt-1">我的</span>
        </a>
      </div>
    </footer>
  </div>
</template>

<style scoped>
a {
  cursor: pointer;
}
</style>
